﻿using System;
using System.Text.RegularExpressions;

namespace Yz.Core.DBUtility
{
    /// <summary>
    ///     EF自动迁移拦截器
    /// </summary>
    public static class EFMigrationInterceptor
    {
        /// <summary>
        ///     检测是不是数据迁移语句
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static bool CheckEFMigration(this string sql)
        {
            var isMigration = false;
            if (sql.Contains("CREATE") || sql.Contains("DROP")
                                       || sql.Contains("ALTER") || sql.Contains("INSERT [dbo].[__MigrationHistory]"))
                isMigration = true;
            return isMigration;
        }

        /// <summary>
        ///     检查这条语句是否是更新表[__MigrationHistory]
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static bool IsUpdateDB(this string sql, ref string newsql)
        {
            var isMigration = false;
            if (sql.Contains("INSERT [dbo].[__MigrationHistory]"))
            {
                var reg = new Regex(@"\d.*_AutomaticMigration");
                if (reg.IsMatch(sql))
                {
                    var match = reg.Match(sql);
                    var value = match.Groups[0].Value;
                    newsql = reg.Replace(sql,
                        string.Format("AutomaticMigration_{0}", DateTime.Now.ToString("yyyyMMddHHmmssffff")));
                }

                isMigration = true;
            }

            return isMigration;
        }

        /// <summary>
        ///     检测是不是增删改语句
        /// </summary>
        /// <param name="sql">检查的语句</param>
        /// <returns></returns>
        public static bool CheckSqlDML(this string sql)
        {
            var isMigration = false;
            if (sql.Contains("INSERT") || sql.Contains("UPDATE") || sql.Contains("DELETE")) isMigration = true;
            return isMigration;
        }
    }
}
